var appFormly = angular.module('formlyExample', [
    'formly', 'formlyBootstrap', 'ui.bootstrap',
    'ngSanitize','ui.select','ui.grid']);
app.requires.push('formlyExample');
// var appFormly = angular.module('formlyExample', [
//     'formly', 'formlyBootstrap','ui.bootstrap',
//     'ngSanitize','ui.select','ui.grid'],

appFormly.config(
    function config(formlyConfigProvider) {
        //格式转换方法 XXX-XXX转驼峰命名
        function camelize(string) {
            string = string.replace(/[\-_\s]+(.)?/g, function(match, chr) {
                return chr ? chr.toUpperCase() : '';
            });
            // Ensure 1st char is always lowercase
            return string.replace(/^([A-Z])/, function(match, chr) {
                return chr ? chr.toLowerCase() : '';
            });
        }
        //获取ngModelAttr对象设置
        function getNgModelAttr(attrs,bindings){
            var ngModelAttrs = {};
            angular.forEach(attrs, function(attr) {
                ngModelAttrs[camelize(attr)] = {attribute: attr};
            });

            angular.forEach(bindings, function(binding) {
                ngModelAttrs[camelize(binding)] = {bound: binding};
            });
            return ngModelAttrs;
        }

        formlyConfigProvider.setWrapper({
          name: 'bootstrapLabel',
          templateUrl: 'assets/views/customform/tpl/normal-label.html'
        });

        formlyConfigProvider.setType({
              name: 'ui-panel',
              templateUrl: 'assets/views/customform/tpl/ui-panel.html'
        });

        formlyConfigProvider.setType({
              name: 'ui-currentuser',
              extends: 'input',
              templateUrl: 'assets/views/customform/tpl/ui-username.html',
              controller: ['$scope',function($scope){
                    if($scope.options.templateOptions.user){
                        $scope.model[$scope.options.key] = $scope.options.templateOptions.user;
                        $scope.options.initialValue = $scope.model[$scope.options.key];
                    }
              }]
        });

        //重构组件模板
        //只读控件
        formlyConfigProvider.setType({
              name: 'ui-label',
              extends: 'input',
              templateUrl: 'assets/views/customform/tpl/ui-label.html',
              defaultOptions:function(options){
                    return {
                        templateOptions: {
                            translate:'',
                            refreshDelay: 0
                        }
                    }
              },
              controller: ['$scope',function($scope){
                    var value = $scope.model[$scope.options.key];
                    function treeDesc(children, key, label){
                        if(label==""){
                            label = children[key];
                        }else{
                           label = children[key] + "-" +label; 
                        }
                        if(angular.isDefined(children.parent)){
                            treeDesc(children.parent,key,label);
                        }else{
                            return label;
                        }
                    }
                    if(angular.isArray(value)){                          
                        var tempValue="";
                        angular.forEach(value, function(item){
                            if(tempValue!=""){
                                tempValue = tempValue + "," ;
                            }
                            tempValue = tempValue + item[$scope.options.templateOptions.labelProp]||item;
                        });
                        $scope.options.templateOptions.translate = tempValue;
                    // }

                    // if(angular.isArray(value)){
                    //     //value = 
                    //     var tempValue;
                    //     angular.forEach(value, function(item){
                    //         tempValue = item[$scope.options.templateOptions.labelProp]||item + '/';
                    //     });
                    //     $scope.options.templateOptions.translate = tempValue;
                    }else if(angular.isObject(value)){
                        if(angular.isDefined(value.children)||angular.isDefined(value.parent)){
                            //tree
                            console.log("value.parent="+JSON.stringify(value.parent))
                            var nameLabel = value[$scope.options.templateOptions.labelProp];
                            nameLabel = treeDesc(value.parent,$scope.options.templateOptions.labelProp,nameLabel);
                            $scope.options.templateOptions.translate = nameLabel;
                        }else{
                            $scope.options.templateOptions.translate = value;
                        }

                    }else if(angular.isString(value)&&value.indexOf('yyyy-MM-ddTHH:mm:sssZ')>0){
                        console.log("value="+value);
                        $scope.options.templateOptions.translate = value;
                    }else{ 
                        // console.log("$scope.options.templateOptions.translate="+JSON.stringify($scope.options.templateOptions.translate))
                        $scope.options.templateOptions.translate = value;
                    }
                    if(angular.isFunction($scope.options.templateOptions.transform)){
                        // console.log("$scope.options.templateOptions.transform22="+JSON.stringify($scope.options.templateOptions.transform))
                        $scope.options.templateOptions.translate = $scope.options.templateOptions.transform($scope.originalModel, value);
                    }
                    //$scope.options.templateOptions.translate = value;
                    // if(angular.isDefined($scope.options.templateOptions.labelProp)){
                    //     $scope.model[$scope.options.key][$scope.options.templateOptions.labelProp]=value;
                    // }else{
                    //     $scope.model[$scope.options.key] = value;
                    // }
                    //$scope.model[$scope.options.key]=value;
              }]
        });


        //标题组件
        formlyConfigProvider.setType({
            name: 'ui-title',
            template: '<section id="page-title-form"><div class="row"><div class="col-sm-8"><h1 class="mainTitle" style="font-weight:bold">{{options.templateOptions.label}}</h1><span class="mainDescription">{{options.templateOptions.placeholder}}</span></div></div></section>'
        });
        //按钮组
        formlyConfigProvider.setType({
            name: 'ui-button',
            templateUrl: 'assets/views/customform/tpl/ui-button.html',
            defaultOptions:function(options){
                return {
                    noFormControl: true
                }
            }
        });
        //3d组link
        formlyConfigProvider.setType({
            name: 'ui-link',
            templateUrl: 'assets/views/customform/tpl/ui-link.html',
            defaultOptions:function(options){
                return {
                    noFormControl: true
                }
            }
        });

        //隐藏域组件
        formlyConfigProvider.setType({
            name: 'ui-hidden',
            extends: 'input',
            template: '<input type="text" ng-model="model[options.key]" style="display: none;"/ >',
            defaultOptions:function(options){
                return {
//                noFormControl: true
                };
            }
        });
        //文本框组件
        formlyConfigProvider.setType({
            name: 'ui-input',
            extends: 'input',
            templateUrl : 'assets/views/customform/tpl/ui-input.html',
            defaultOptions:function(options){
                return {
                };
            }
        });
        //数字组件
        formlyConfigProvider.setType({
            name: 'ui-number',
            extends: 'input',
            templateUrl : 'assets/views/customform/tpl/ui-number.html',
            defaultOptions:function(options){
                return {
                };
            }
        });



        //下拉框组件
        formlyConfigProvider.setType({
            name: 'ui-select',
            extends: 'select',
            templateUrl : 'assets/views/customform/tpl/ui-select.html',
            defaultOptions:function(options){
                return{
                    templateOptions: {
                        refresh:function(){},
                        refreshDelay: 0,
                        linkage:function(modelName, data, model, modelKey, key){
                            angular.extend(data,{"idx":0,"sum":1});
                            options.templateOptions.APIService.fetchDataList(modelName, data).then(function(response){
                                var myData = options.templateOptions.Restangular.stripRestangular(response);
                                var list = myData.list;
                                if(list.length == 1){
                                    angular.forEach(model.$parent.fields,function(item){
                                        if(item.templateOptions.pkey==modelKey + "." + key){
                                            item.value(list[0][key][item.key]);
                                        }
                                    })
                                }
                            });
                        }
                    }
                };
            }
        });
        //下拉多选框组件
        formlyConfigProvider.setType({
            name: 'ui-multiselect',
            extends: 'select',
            templateUrl : 'assets/views/customform/tpl/ui-multiselect.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        refresh:function(){},
                        refreshDelay: 0
                    }
                };
            },
            controller: ['$scope',function($scope){
                $scope.model[$scope.options.key]=[];
            }]
        });

        //下拉多选框灵活组件
        formlyConfigProvider.setType({
            name: 'ui-multiselectplus',
            extends: 'select',
            templateUrl : 'assets/views/customform/tpl/ui-multiselectplus.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        refreshData:function(search, options, model, that){
                            var process = options.templateOptions.ApiService.all("");
                            if(search){

                            }else{

                            }
                            var postData = options.templateOptions.optionsPostData;
                            if(angular.isFunction(options.templateOptions.optionsPostData)){
                                postData = options.templateOptions.optionsPostData(options, model, that);
                            }
                            process.customPOST(postData,options.templateOptions.optionsUrl).then(function(result){
                                if(!options.templateOptions.options){
                                    options.templateOptions.options=[];
                                }
                                if(options.templateOptions.optionsDataKey){
                                    options.templateOptions.options =result[options.templateOptions.optionsDataKey];
                                }else{
                                    options.templateOptions.options =result;
                                }
                                if(options.templateOptions.optionsChecked){
                                    options.value(options.templateOptions.options);
                                }
                            });
                        },
                        refreshDelay: 0
                    }
                };
            },
            controller: ['$scope',function($scope){
                if(angular.isArray($scope.model[$scope.options.key])){

                }else{
                    $scope.model[$scope.options.key]=[];
                }
            }]

        });

        //多选下拉框组件
        formlyConfigProvider.setType({
            name: 'ui-multi-select-tree',
            extends: 'multiCheckbox',
            templateUrl : 'assets/views/customform/tpl/ui-multi-select-tree.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        refresh: function(items) {
                            //console.log(items);
                            function convertListToTree(data, treeMap){
                                var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
                                var root = null; //Initially set our loop to null

                                //loop over data
                                for(var i = 0; i < data.length; i++) {
                                    var datum = data[i];
                                    //each node will have children, so let's give it a "children" poperty
                                    datum.children = [];

                                    //add an entry for this node to the map so that any future children can
                                    //lookup the parent
                                    idToNodeMap[datum.id] = datum;

                                    //Does this node have a parent?
                               // console.log("datum="+JSON.stringify(datum))

                                    if(typeof datum.parent === "undefined") {
                                         
                                        //Doesn't look like it, so this node is the root of the tree
                                        root = datum;
                                        treeMap[datum.id] = root;
                                    
                                    } else {  
                                       
                                        //This node has a parent, so let's look it up using the id
                                        parentNode = idToNodeMap[datum.parent.id];

                                        //We don't need this property, so let's delete it.
                                        delete datum.parent;

                                        //Let's add the current node as a child of the parent node.
                                        parentNode.children.push(datum);        

                                    }
                                }
                                return root;
                            }

                            function convertParentToChildList(data){
                                // console.log("data="+JSON.stringify(data))
                                var treeMap = {};
                                var list=[];
                                convertListToTree(data, treeMap);
                                angular.forEach(treeMap,function(item){
                                    // console.log("item="+JSON.stringify(item))
                                    list.push(item);
                                });
                                return list;
                            }

                            function selectItem(pmodel, childrens){
                                if(angular.isArray(pmodel)){

                                }else{
                                    if(pmodel && pmodel.id){
                                        angular.forEach(childrens,function(item){
                                            if(item.id == pmodel.id){
                                                item.selected = true;
                                            }
                                            if (item && item.children) {
                                              selectItem(pmodel ,item.children);
                                            }
                                        });
                                    }
                                }
                            }

                            options.templateOptions.refreshData(options.templateOptions.APIService).then(function(result){
                                if(!options.templateOptions.options){
                                    options.templateOptions.options=[];
                                }
                                if(options.templateOptions.optionsDataKey){
                                    options.templateOptions.options = convertParentToChildList(result[options.templateOptions.optionsDataKey]);
                                }else{
                                    options.templateOptions.options = convertParentToChildList(result);
                                }

                                //set default value
                                var pmodel,i=0;
                                if(options.templateOptions.pkey){
                                    if(options.templateOptions.pkey.indexOf(".")>0){
                                        angular.forEach(options.templateOptions.pkey.split("."),function(p){
                                            if(i==0){
                                                if(options.model[p]==null){
                                                    options.model[p] = {};
                                                }
                                                pmodel = options.model[p];
                                                i++;
                                            }else{
                                                if(pmodel[p]==null){
                                                    pmodel[p] = {};
                                                }
                                                pmodel = pmodel[p];
                                            }
                                        });
                                    }else{
                                        pmodel = options.model[options.templateOptions.pkey];
                                    }
                                }
                                if(pmodel){
                                    pmodel = pmodel[options.key];
                                }else{
                                    pmodel = options.model[options.key];
                                }
                                if(pmodel && pmodel.id){
                                    selectItem(pmodel, options.templateOptions.options);
                                }                                

                                items.inputModel = options.templateOptions.options;                             
                            });
                        }
                    },
                    validators:{
                        required:{
                            expression: function(viewValue, modelValue){
                                var value = modelValue || viewValue;
                                if(angular.isArray(value)){
                                    return value.length>0
                                }else{
                                    return value!=null;
                                }
                            }
                        }
                    }
                }
            },
            controller: ['$scope',function($scope){
                if($scope.options.templateOptions.isMultiSelect){

                }else{
                    if($scope.model[$scope.options.key]){
                        //console.log($scope.inputModel);
                    }
                }
                //$scope.model[$scope.options.key]=[];
            }]
        });
        //勾选组件
        formlyConfigProvider.setType({
            name: 'ui-checkbox',
            extends: 'checkbox',
            templateUrl : 'assets/views/customform/tpl/ui-checkbox.html'
        });
        //多选框组件
        formlyConfigProvider.setType({
            name: 'ui-checklist',
            extends: 'multiCheckbox',
            templateUrl : 'assets/views/customform/tpl/ui-checklist.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        refresh:function(){},
                        refreshDelay: 0
                    }
                };
            }
        });
        //单选框组件
        formlyConfigProvider.setType({
            name: 'ui-radio',
            extends: 'radio',
            templateUrl : 'assets/views/customform/tpl/ui-radio.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        refresh:function(){},
                        refreshDelay: 0
                    }
                };
            }
        });
        //文本域组件
        // formlyConfigProvider.setType({
        //     name: 'ui-textarea',
        //     extends: 'textarea',
        //     templateUrl : 'assets/views/customform/tpl/ui-textarea.html',
        //     defaultOptions:function(options){
        //             return {
        //                 templateOptions: {
        //                     transform:function(model, value){
        //                         return value;
        //                     },
        //                 },
        //                 validation: {
        //                     messages:{
        //                         maxlength: function(viewValue, modelValue, scope){
        //                             return scope.to.label + '字数超长';
        //                         }
        //                     }
        //                 }
        //             }
        //     },
        //     controller: ['$scope',function($scope){
        //         var value = $scope.model[$scope.options.key];
        //         if(angular.isFunction($scope.options.templateOptions.transform)){
        //             $scope.model[$scope.options.key] = $scope.options.templateOptions.transform($scope.originalModel, value);
        //         }
        //     }]
        // });

      
//文本域组件
        formlyConfigProvider.setWrapper({
          name: 'validation',
          types: ['ui-textarea'],
          template: "<formly-transclude></formly-transclude><div class=\"has-error\" ng-messages=\"fc.$error\" ng-if=\"options.formControl.$touched\"><div class=\"error\" ng-message=\"{{::name}}\" ng-repeat=\"(name, message) in ::options.validation.messages\">{{message(fc.$viewValue, fc.$modelValue, this)}}</div></div>"
        });

        formlyConfigProvider.setType({
            name: 'ui-textarea',
            extends: 'textarea',
            templateUrl : 'assets/views/customform/tpl/ui-textarea.html',
            defaultOptions:function(options){
                    return {
                        templateOptions: {
                            transform:function(model, value){
                                return value;
                            },
                        },
                        validation: {
                          messages: {
                            maxlength: function(viewValue, modelValue, scope) {
                                if(viewValue!=null){ 
                                    if(viewValue.length>scope.to.maxlength){
                                        return scope.to.label + ' 字数('+ viewValue.length +')超限('+scope.to.maxlength+')'
                                    }else{
                                        return "";
                                    }
                                }                        
                            }
                          }
                        }
                    }
            },
            controller: ['$scope',function($scope){
                var value = $scope.model[$scope.options.key];
                if(angular.isFunction($scope.options.templateOptions.transform)){
                    $scope.model[$scope.options.key] = $scope.options.templateOptions.transform($scope.originalModel, value);
                }
            }]
        });


        //文本框自定义选择面板组件
        formlyConfigProvider.setType({
            name: 'ui-input-selectmodal',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-input-selectmodal.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        openModal: function (size,options,modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/modal-content.html',
                                controller: 'ModalInstanceCtrl',//'CustomformCtrl',//
                                size: size,
                                resolve: options.templateOptions.modalParam
                            });
                            modalInstance.result.then(function (selectedItem) {
                                options.value(selectedItem);
                            }, function () {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            }
        });
        //日期控件
        var datepicker_attr = [
            'date-disabled',
            'custom-class',
            'show-weeks',
            'starting-day',
            'init-date',
            'min-mode',
            'max-mode',
            'format-day',
            'format-month',
            'format-year',
            'format-day-header',
            'format-day-title',
            'format-month-title',
            'year-range',
            'shortcut-propagation',
            'datepicker-popup',
            'show-button-bar',
            'current-text',
            'clear-text',
            'close-text',
            'close-on-date-selection',
            'datepicker-append-to-body'
        ];
        var datepicker_bindings = [
            'datepicker-mode',
            'min-date',
            'max-date'
        ];
        //日期控件
        formlyConfigProvider.setType({
            name: 'ui-datepicker',
            templateUrl: 'assets/views/customform/tpl/ui-datepicker.html',
            extends: 'input',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions: {
                ngModelAttrs: getNgModelAttr(datepicker_attr,datepicker_bindings),
                templateOptions: {
                    datepickerPopup: 'yyyy-MM-dd HH:mm:ss'
                }
            },
            controller: ['$scope', '$filter', function ($scope, $filter) {
                $scope.model[$scope.options.key] = $filter('date')(new Date(),$scope.options.templateOptions.datepickerPopup);
                $scope.options.initialValue = $scope.model[$scope.options.key];
                $scope.endOpen = true;
                $scope.datepicker = {};
                $scope.datepicker.opened = false;
                $scope.datepicker.open = function ($event) {
                     $scope.datepicker.opened = true;
                };
            }]
        });
        //用户单选控件
        formlyConfigProvider.setType({
            name: "ui-requesterselect",
            templateUrl: 'assets/views/customform/tpl/ui-requester.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        openModal: function(size, options, modal) {
                            var modelObject = options.value();
                            
                            var searchModal = function(filterSearchData){
                                    var modalInstance = modal.open({
                                        templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                        controller: function($scope,i18nService, $modalInstance, items, title, Restangular, APIService, language, searchData) {
                                            $scope.langs=i18nService.getAllLangs();
                                            $scope.lang = 'zh-cn';
                                            i18nService.setCurrentLang($scope.lang);
                                            $scope.gridOptions = {};
                                            $scope.gridOptions.data = 'myData';
                                            $scope.gridOptions.enableColumnResizing = true;
                                            $scope.gridOptions.enableFiltering = false;
                                            $scope.gridOptions.enableGridMenu = false;
                                            $scope.gridOptions.showGridFooter = true;
                                            $scope.gridOptions.showColumnFooter = true;
                                            $scope.gridOptions.fastWatch = true;
                                            $scope.gridOptions.useExternalPagination = true;
                                            $scope.gridOptions.paginationPageSizes = [10];
                                            $scope.gridOptions.paginationPageSize = 10;
                                            $scope.gridOptions.multiSelect = false;

                                            $scope.gridOptions.rowIdentity = function(row) {
                                                return row.id;
                                            };
                                            $scope.gridOptions.getRowIdentity = function(row) {
                                                return row.id;
                                            };
                                            //{"id":1,"phone":"15071189091","name":"管理员","gender":"男","flag":1,"email":"asda@qq.com","account":"000001","group":[{"id":3,"groupName":"运行监控科"}]}
                                            $scope.gridOptions.columnDefs = [
                                                { name:'account', displayName:'账号', width:140},
                                                { name:'name', displayName:'名称', width:100},
                                                { name:'gender', displayName:'性别', width:140},
                                                { name:'phone', displayName:'电话', width:100},
                                                { name:'email', displayName:'邮件', width:100},
                                                { name:'dept.dept', displayName:'部门', width:100},
                                                { name:'group[0].groupName', displayName:'职位', width:100}
                                            ];

                                            $scope.gridOptions.onRegisterApi = function(gridApi){
                                                $scope.gridApi = gridApi;
                                                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                                                    $scope.loadData({"idx":newPage-1,"sum":pageSize});                                             
                                                });

                                                gridApi.selection.on.rowSelectionChanged($scope, function(data){
                                                    $scope.selected.item = data.entity;
                                                    console.log(data);
                                                });
                                            };

                                            $scope.loadData=function(filterData){
                                                items.fetchItems(filterData, APIService).then(function(data){
                                                    var myData = Restangular.stripRestangular(data);
                                                    $scope.gridOptions.totalItems = myData.totalNum;
                                                    $scope.myData = myData.list;
                                                });
                                            };
                                            $scope.title = title;
                                            if(searchData){
                                                $scope.loadData(searchData);
                                            }else{
                                                $scope.loadData({
                                                    idx:0,
                                                    sum:10
                                                });
                                            }
                                            

                                            $scope.selected = {
                                                item: {}
                                            };

                                            $scope.ok = function() {
                                                $modalInstance.close($scope.selected.item);
                                            };

                                            $scope.cancel = function() {
                                                $modalInstance.dismiss('cancel');
                                            };
                                        },
                                        size: size,
                                        resolve: {
                                            items: function() {
                                                return  {
                                                    fetchItems : function(filterData,APIService){
                                                        filterData = filterData || {};
                                                        if(angular.isUndefined(filterData.idx)||filterData.idx==null){
                                                            filterData = {
                                                                idx:0,
                                                                sum:10
                                                            };
                                                        } 
                                                        return options.templateOptions.fetchItems(filterData,APIService);
                                                    }
                                                };
                                            },
                                            title: function() {
                                                return options.templateOptions.modalTitle;
                                            },
                                            Restangular : function() {
                                                return options.templateOptions.Restangular;
                                            },
                                            APIService: function() {
                                                return options.templateOptions.ApiService;
                                            },
                                            language: function(){
                                                return options.templateOptions.language;
                                            },
                                            searchData: function(){
                                                return filterSearchData;
                                            }
                                        }
                                    });
                                    modalInstance.result.then(function(selectedItem) {
                                        options.value(selectedItem);
                                        if(options.templateOptions.callback&&angular.isFunction(options.templateOptions.callback)){
                                            options.templateOptions.callback(selectedItem, options);
                                        }
                                    }, function() {
                                        //console.log('Modal dismissed at: ' + new Date());
                                    });
                            }
                            if(modelObject!=null&&angular.isDefined(modelObject.account)){
                                var searchAccount=modelObject.account;
                                if(searchAccount.length==6){
                                    var filterData = {
                                        'requester':{
                                            'account':searchAccount
                                        },
                                        idx:0,
                                        sum:10
                                    };
                                    options.templateOptions.ApiService.fetchDataList('requester',filterData).then(function(data){
                                            var myData = options.templateOptions.Restangular.stripRestangular(data);
                                            if(myData.list.length>=1){
                                                if(myData.list.length==1){
                                                    options.value(myData.list[0]);
                                                }else{
                                                    searchModal(filterData);
                                                }
                                            }else{
                                                searchModal();
                                            }
                                        });
                                }else{
                                    searchModal();
                                }
                            }else{
                                searchModal();
                            }                            
                        },
                        addRequeter: function(size, options, modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/modal-add-requester.html',
                                controller: function($scope, $modalInstance, items, title, Restangular, APIService, UserService) {
                                    $scope.title = "新增请求人";
                                    
                                    $scope.requester = {

                                    };

                                    $scope.refreshDepts = function(key){
                                        var filterData = {
                                            'idx':0,
                                            'sum':5,
                                            'dept':{
                                                'name':key
                                            }
                                        };
                                        UserService.fetchDataList('department', filterData).then(function(response){
                                            if(response.status==200){
                                                $scope.depts = response.list;
                                            }
                                        })
                                    }

                                    $scope.ok = function() {
                                        $modalInstance.close($scope.requester);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return  {
                                            fetchItems : function(filterData,APIService){
                                                filterData = filterData || {};
                                                if(!filterData.idx){
                                                    filterData = {
                                                        idx:0,
                                                        sum:10
                                                    };
                                                } 
                                                return options.templateOptions.fetchItems(filterData,APIService);
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular : function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    UserService: function() {
                                        return options.templateOptions.UserService;
                                    }
                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                if(selectedItem){
                                    var data = {
                                        'requester': selectedItem
                                    };
                                    options.templateOptions.UserService.addData('requester', data).then(function(response){
                                        if(response.status==200){
                                            options.value(response.data);
                                        }
                                    })
                                }                                
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            },
            controller:['$scope', function($scope){
                $scope.options.templateOptions.that = $scope;
            }]
        });



        //用户单选控件
        formlyConfigProvider.setType({
            name: "ui-userselect",
            templateUrl: 'assets/views/customform/tpl/ui-userselect.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        openModal: function(size, options, modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                controller: function($scope, i18nService, $modalInstance, items, title, Restangular, APIService, onDataCallback, parentScope) {
                                    $scope.langs=i18nService.getAllLangs();
                                    $scope.lang = 'zh-cn';
                                    i18nService.setCurrentLang($scope.lang);
                                    $scope.gridOptions = {};
                                    $scope.gridOptions.data = 'myData';
                                    $scope.gridOptions.enableColumnResizing = true;
                                    $scope.gridOptions.enableFiltering = true;
                                    $scope.gridOptions.enableGridMenu = false;
                                    $scope.gridOptions.showGridFooter = true;
                                    $scope.gridOptions.showColumnFooter = true;
                                    $scope.gridOptions.fastWatch = true;
                                    $scope.gridOptions.useExternalFiltering=true;
                                    $scope.gridOptions.useExternalPagination = true;
                                    $scope.gridOptions.paginationPageSizes = [10];
                                    $scope.gridOptions.paginationPageSize = 10;
                                    $scope.gridOptions.multiSelect = false;

                                    $scope.gridOptions.rowIdentity = function(row) {
                                        return row.id;
                                    };
                                    $scope.gridOptions.getRowIdentity = function(row) {
                                        return row.id;
                                    };
                                    //{"id":1,"phone":"15071189091","name":"管理员","gender":"男","flag":1,"email":"asda@qq.com","account":"000001","group":[{"id":3,"groupName":"运行监控科"}]}
                                    $scope.gridOptions.columnDefs = [
                                        // { name:'id', width:80, enableFiltering:false},
                                        { name:'account', displayName:'工号', width:140},
                                        { name:'name', displayName:'名称', width:100},
                                        { name:'gender', displayName:'性别', width:140, enableFiltering:false},
                                        { name:'phone', displayName:'电话', width:100, enableFiltering:false},
                                        { name:'email', displayName:'邮件', width:100, enableFiltering:false},
                                        { name:'dept.dept', displayName:'部门', width:100, enableFiltering:false},
                                        { name:'role[0].role', displayName:'职位', width:100, enableFiltering:false}
                                    ];

                                    $scope.gridOptions.onRegisterApi = function(gridApi){
                                        $scope.gridApi = gridApi;
                                        gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                                            var filtersData = $scope.memoryfilterData;
                                            filtersData.idx=newPage-1;
                                            filtersData.sum=pageSize;
                                            $scope.loadData(filtersData);    
                                            //console.log(pageSize);
                                            // $scope.loadData({"idx":newPage-1,"sum":pageSize});                                            
                                        });

                                        gridApi.selection.on.rowSelectionChanged($scope, function(data){
                                            $scope.selected.item = data.entity;
                                            //console.log(data);
                                        });
                                        gridApi.core.on.filterChanged( $scope, function() {
                                            var grid = this.grid;

                                            var filtersData = {
                                                    idx:0,
                                                    sum:10,
                                                    "user":{"roledata":{"rolecode":"roleset"}}
                                            };
                                            angular.forEach(grid.columns,function(item){
                                                if(item.enableFiltering){
                                                   console.log("item.filters[0]="+JSON.stringify(item.filters)); 
                                                    if(angular.isDefined(item.filters[0].term)&&item.filters[0].term!=''){
                                                        if(angular.isUndefined(filtersData['user'])){
                                                            filtersData['user']={};
                                                        }
                                                        filtersData['user'][item.field]=item.filters[0].term;
                                                    }                                                
                                                }
                                            });
                                            $scope.memoryfilterData = filtersData;
                                            $scope.loadData(filtersData);
                                        });

                                    };
                                    $scope.memoryfilterData = {
                                                    "idx":0,
                                                    "sum":10,
                                                    "user":{"roledata":{"rolecode":"roleset"}}
                                                }

                                    $scope.loadData=function(filterData){
                                        console.log("filtersData=111"+JSON.stringify(filterData))
                                        items.fetchItems(filterData, APIService).then(function(data){
                                            var myData = Restangular.stripRestangular(data);
                                            $scope.gridOptions.totalItems = myData.totalNum;
                                            $scope.myData = myData.list;
                                        });
                                    };
                                    $scope.title = title;
                                    
                                    $scope.loadData({
                                        idx:0,
                                        sum:10,
                                        "user":{"roledata":{"rolecode":"roleset"}}
                                    });

                                    $scope.selected = {
                                        item: {}
                                    };

                                    $scope.ok = function() {
                                        // if(onDataCallback&&angular.isFunction(onDataCallback)){
                                        //     onDataCallback($scope.selected.item, parentScope);
                                        // }
                                        $modalInstance.close($scope.selected.item);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return  {
                                            fetchItems : function(filterData,APIService){
                                                filterData = filterData || {};
                                                if(angular.isDefined(filterData.idx) &&filterData.idx==null){
                                                    filterData = { 
                                                        idx:0,
                                                        sum:10,
                                                        "user":{"roledata":{"rolecode":"roleset"}}
                                                    };
                                                } 
                                                return options.templateOptions.fetchItems(filterData,APIService);
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular : function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    onDataCallback: function() {
                                        return options.templateOptions.callback;
                                    },
                                    parentScope: function() {
                                        return options.templateOptions.that;
                                    }

                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                               // console.log(selectedItem);
                                options.value(selectedItem);
                                if(options.templateOptions.callback&&angular.isFunction(options.templateOptions.callback)){
                                    options.templateOptions.callback(selectedItem, options.templateOptions.that);
                                }
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            },
            controller:['$scope', function($scope){
                $scope.options.templateOptions.that = $scope;
            }]
        });
        //用户多选控件
        formlyConfigProvider.setType({
            name: "ui-multiuserselect",
            templateUrl: 'assets/views/customform/tpl/ui-multiuserselect.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        openModal: function(size, options, modal, model) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                controller: function($scope, $modalInstance,i18nService, $timeout, items, title, Restangular, APIService, selectItems) {
                                    $scope.langs=i18nService.getAllLangs();
                                    $scope.lang = 'zh-cn';
                                    i18nService.setCurrentLang($scope.lang);
                                    $scope.gridOptions = {};
                                    $scope.gridOptions.data = 'myData';
                                    $scope.gridOptions.enableColumnResizing = true;
                                    $scope.gridOptions.enableFiltering = true;
                                    $scope.gridOptions.enableGridMenu = true;
                                    $scope.gridOptions.showGridFooter = true;
                                    $scope.gridOptions.showColumnFooter = true;
                                    $scope.gridOptions.fastWatch = true;
                                    $scope.gridOptions.useExternalFiltering=true;
                                    $scope.gridOptions.useExternalPagination = true;
                                    $scope.gridOptions.paginationPageSizes = [10];
                                    $scope.gridOptions.paginationPageSize = 10;
                                    $scope.gridOptions.multiSelect = true;

                                    $scope.gridOptions.rowIdentity = function(row) {
                                        return row.id;
                                    };
                                    $scope.gridOptions.getRowIdentity = function(row) {
                                        return row.id;
                                    };
                                    //{"id":1,"phone":"15071189091","name":"管理员","gender":"男","flag":1,"email":"asda@qq.com","account":"000001","group":[{"id":3,"groupName":"运行监控科"}]}
                                    $scope.gridOptions.columnDefs = [
                                        // { name:'id', width:80, enableFiltering:false},
                                        { name:'account', displayName:'账号', width:140},
                                        { name:'name', displayName:'名称', width:100},
                                        { name:'gender', displayName:'性别', width:140, enableFiltering:false},
                                        { name:'phone', displayName:'电话', width:100, enableFiltering:false},
                                        { name:'email', displayName:'邮件', width:100, enableFiltering:false},
                                        { name:'dept.dept', displayName:'部门', width:100, enableFiltering:false},
                                        { name:'group[0].groupName', displayName:'职位', width:100, enableFiltering:false}
                                    ];

                                    $scope.selected = {
                                        items: selectItems
                                    };
                                    $scope.gridOptions.onRegisterApi = function(gridApi){
                                        $scope.gridApi = gridApi;
                                        gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                                            var filtersData = $scope.memoryfilterData;
                                            filtersData.idx=newPage-1;
                                            filtersData.sum=pageSize;
                                            $scope.loadData(filtersData); 
                                            // $scope.loadData({"idx":newPage-1,"sum":pageSize});                                            
                                        });
                                        gridApi.selection.on.rowSelectionChanged($scope, function(scope){
                                            var j=0;
                                            for(var i=0;i<=scope.grid.appScope.selected.items.length;i++){
                                                if(scope.grid.appScope.selected.items[i]==scope.entity){
                                                    j++;
                                                    break;
                                                }
                                            }
                                            if(j==1){
                                                scope.grid.appScope.selected.items.splice(i,1);
                                            }else{
                                                scope.grid.appScope.selected.items.push(scope.entity)
                                                for(var i=0;i<scope.grid.appScope.selected.items.length;i++){
                                                    for(var z=0;z<scope.grid.appScope.selected.items.length;z++){ 
                                                    // console.log("$scope.selected.items="+JSON.stringify($scope.selected.items));
                                                    // console.log("scope.grid.appScope.selected.items="+JSON.stringify(scope.grid.appScope.selected.items))
                                                        if(angular.isDefined(scope.grid.appScope.selected.items) && scope.grid.appScope.selected.items[i].id==scope.grid.appScope.selected.items[z].id&&i!=z){
                                                            scope.grid.appScope.selected.items.splice(i,1);
                                                        }         
                                                    }
                                                }
                                            }
                                        });
                                        // gridApi.selection.on.rowSelectionChanged($scope, function($scope, rows){
                                           
                                        //     $scope.grid.appScope.selected.items.push($scope.entity);
                                        // });
                                         gridApi.core.on.filterChanged( $scope, function() {
                                            var grid = this.grid;
                                            var filtersData = {
                                                    idx:0,
                                                    sum:10,
                                                    "user":{"roledata":{"rolecode":"roleset"}}
                                            };
                                            angular.forEach(grid.columns,function(item){
                                                if(item.enableFiltering){
                                                    //console.log("filtersData="+JSON.stringify(filtersData))
                                                    if(angular.isDefined(item.filters[0].term)&&item.filters[0].term!=''){
                                                        if(angular.isUndefined(filtersData['user'])){
                                                            filtersData['user']={};
                                                        }
                                                        filtersData['user'][item.field]=item.filters[0].term;
                                                    }                                                
                                                }
                                            });
                                            $scope.memoryfilterData = filtersData;
                                            $scope.loadData(filtersData);
                                        });

                                    };
                                    $scope.memoryfilterData = {
                                        "idx":0,
                                        "sum":10,
                                        "user":{"roledata":{"rolecode":"roleset"}}
                                    }
                                    $scope.loadData=function(filterData){
                                        // console.log(" filtersData['user'][item.field]=111"+JSON.stringify(filterData));
                                        items.fetchItems(filterData, APIService).then(function(data){
                                            var myData = Restangular.stripRestangular(data);
                                            $scope.gridOptions.totalItems = myData.totalNum;
                                            $scope.myData = myData.list;
                                            //console.log($scope.gridOptions.pagination.getTotalPages());
                                            // if($scope.selected.items){
                                            //     angular.forEach($scope.selected.items,function(selectItem){
                                            //         $scope.gridApi.selection.selectRow(selectItem);
                                            //     });
                                            // }
                                        });
                                    };
                                    $scope.title = title;
                                    
                                    $scope.loadData({
                                        idx:0,
                                        sum:10,
                                        "user":{"roledata":{"rolecode":"roleset"}}
                                    });

                                    

                                    // $timeout(function(){
                                    //     if($scope.selected.items){
                                    //         angular.forEach($scope.selected.items,function(selectItem){
                                    //             $scope.gridApi.selection.selectRow(selectItem);
                                    //         });
                                    //     }
                                    // },2000)
                                    


                                    $scope.ok = function() {
                                        // $scope.selected.items = $scope.gridApi.selection.getSelectedRows();
                                        $modalInstance.close($scope.selected.items);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return  {
                                            fetchItems : function(filterData,APIService){
                                                filterData = filterData || {};
                                                if(angular.isDefined(filterData.idx) &&filterData.idx==null){
                                                    filterData = {
                                                        idx:0,
                                                        sum:10,
                                                        "user":{"roledata":{"rolecode":"roleset"}}
                                                    };
                                                } 
                                                return options.templateOptions.fetchItems(filterData,APIService);
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular : function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    selectItems : function() {
                                        return model||[];
                                    }
                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                options.value(selectedItem);
                                options.formControl.$validate();
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    },
                    validators:{
                        required:{
                            expression:function(viewValue, modelValue){
                                var value = modelValue || viewValue;
                                return value.length>=1;
                            }
                        }
                    }
                };
            },
            controller:['$scope', function($scope){
                $scope.model[$scope.options.key] = [];
                $scope.remove = function(itemId){
                    angular.forEach($scope.model[$scope.options.key], function(entry,index){
                        if(entry.id == itemId){
                            $scope.model[$scope.options.key].splice(index,1);
                            console.log($scope.options.formControl)
                            $scope.options.formControl.$validate();
                        }else{
                            
                        }
                    });
                }
            }]
        });


        //选项选择控件
        formlyConfigProvider.setType({
            name: "ui-modelselect",
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-modelselect.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        openModal: function(size, options, modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                controller: function($scope, $modalInstance, items, title, Restangular, APIService,i18nService) {
                                    $scope.langs=i18nService.getAllLangs();
                                    $scope.lang = 'zh-cn';
                                    i18nService.setCurrentLang($scope.lang);
                                    $scope.gridOptions = {};
                                    $scope.gridOptions.data = 'myData';
                                    $scope.gridOptions.enableColumnResizing = true;
                                    $scope.gridOptions.enableFiltering = true;
                                    $scope.gridOptions.enableGridMenu = true;
                                    $scope.gridOptions.showGridFooter = true;
                                    $scope.gridOptions.showColumnFooter = true;
                                    $scope.gridOptions.fastWatch = true;
                                    $scope.gridOptions.useExternalPagination = true;
                                    $scope.gridOptions.useExternalFiltering=true;
                                    $scope.gridOptions.paginationPageSizes = [10];
                                    $scope.gridOptions.paginationPageSize = 10;
                                    $scope.gridOptions.multiSelect = false;

                                    $scope.gridOptions.rowIdentity = function(row) {
                                        return row.id;
                                    };
                                    $scope.gridOptions.getRowIdentity = function(row) {
                                        return row.id;
                                    };
                                    
                                    $scope.gridOptions.columnDefs = items.columnDefs();

                                    $scope.gridOptions.onRegisterApi = function(gridApi){
                                        $scope.gridApi = gridApi;
                                        gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                                            // console.log(newPage);
                                            // console.log(pageSize);
                                            $scope.loadData({"idx":newPage-1,"sum":pageSize});                                            
                                        });

                                        gridApi.core.on.filterChanged( $scope, function() {
                                            var grid = this.grid;
                                            var filtersData = {
                                                    idx:0,
                                                    sum:10
                                            };
                                            angular.forEach(grid.columns,function(item){
                                                if(item.enableFiltering){
                                                    if(angular.isDefined(item.filters[0].term)&&item.filters[0].term!=''){
                                                        // console.log("filtersData="+JSON.stringify(filtersData))
                                                        if(angular.isUndefined(filtersData['incident'])){
                                                            filtersData['incident']={};
                                                        }
                                                        filtersData['incident'][item.field]=item.filters[0].term;
                                                         if(angular.isUndefined(filtersData['problem'])){
                                                            filtersData['problem']={};
                                                        }
                                                        filtersData['problem'][item.field]=item.filters[0].term;
                                                         if(angular.isUndefined(filtersData['change'])){
                                                            filtersData['change']={};
                                                        }
                                                        filtersData['change'][item.field]=item.filters[0].term;
                                                        if(angular.isUndefined(filtersData['release'])){
                                                            filtersData['release']={};
                                                        }
                                                        filtersData['release'][item.field]=item.filters[0].term;
                                                    }                                                
                                                }
                                            });
                                            $scope.loadData(filtersData);
                                        });


                                        gridApi.selection.on.rowSelectionChanged($scope, function(data){
                                            $scope.selected.item = data.entity;
                                            //console.log(data);
                                        });
                                    };

                                    $scope.loadData=function(filterData){
                                        items.fetchItems(filterData, APIService).then(function(data){
                                            var myData = Restangular.stripRestangular(data);
                                            $scope.gridOptions.totalItems = myData.totalNum;
                                            $scope.myData = myData.list;
                                        });
                                    };

                                    $scope.title = title;
                                    
                                    $scope.loadData({
                                        idx:0,
                                        sum:10
                                    });

                                    $scope.selected = {
                                        item: {}
                                    };

                                    $scope.ok = function() {
                                        //console.log($scope.selected.item);
                                        $modalInstance.close($scope.selected.item);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return  {
                                            fetchItems : function(filterData,APIService){
                                                filterData = filterData || {};
                                                // if(!filterData.idx){
                                                if(angular.isDefined(filterData.idx) &&filterData.idx==null){
                                                    filterData = {
                                                        idx:0,
                                                        sum:10
                                                    };
                                                } 
                                                return options.templateOptions.fetchItems(filterData,APIService,options);
                                            },
                                            columnDefs : function(){
                                                return options.templateOptions.columnDefs;
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular : function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    }
                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                options.value(selectedItem);
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            }
        });
        //工单控件
        formlyConfigProvider.setType({
              name: 'ui-workernumber',
              extends:'input',
              templateUrl: 'assets/views/customform/tpl/ui-workernumber.html',
              controller: ['$scope', function ($scope) {
                setTimeout(function(){
                    $scope.options.templateOptions.getWorkernumber($scope.options.templateOptions.ApiService).then(function(result){
                        var modelData = $scope.options.templateOptions.Restangular.stripRestangular(result);
                        if(modelData.status==200){
                            $scope.model[$scope.options.key] = modelData.data;
                            $scope.options.initialValue = $scope.model[$scope.options.key];
                        }
                    });
                },1000);
             }]
        });
        //无上传按钮附件上传组件
        formlyConfigProvider.setType({
            name: 'ui-dropfilenotup',
            templateUrl: 'assets/views/customform/tpl/ui-dropfilenotup.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            controller:['$scope', function ($scope) {
                if(angular.isUndefined($scope.form.dropState)){
                    $scope.form.dropState=false;
                }
                //附件上传数据
                var uploader = $scope.uploader = $scope.options.templateOptions.fileUploader;
                //$scope.options.templateOptions.uploader();
                
                // FILTERS
                uploader.filters.push({
                    name: 'customFilter',
                    fn: function(item /*{File|FileLikeObject}*/ , options) {
                        return this.queue.length < 10;
                    }
                });


                $scope.dropfile = function(APIService, processInstanceId, taskId, userId){
                    uploader.onBeforeUploadItem = function(item) {
                        item.url = APIService.saveAttachments(processInstanceId, taskId, userId).getRequestedUrl();
                        item.formData.push({'fileName':item.file.name});
                        console.info('onBeforeUploadItem', item);
                    };
                    uploader.uploadAll();
                }

                // CALLBACKS
                uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
                    console.info('onWhenAddingFileFailed', item, filter, options);
                };
                uploader.onAfterAddingFile = function(fileItem) {
                    console.info('onAfterAddingFile', fileItem);
                };
                uploader.onAfterAddingAll = function(addedFileItems) {
                    console.info('onAfterAddingAll', addedFileItems);
                };
                uploader.onBeforeUploadItem = function(item) {
                    // if($scope.uploader.getNotUploadedItems().length>0&&response.data.processInstanceId){
                                    //     // $scope.uploader.options.url();
                                    //     $scope.uploader.onBeforeUploadItem = function(item) {
                                    //         item.url = api_bpm_domain.saveAttachments($stateParams.processInstanceId,$stateParams.taskId,$scope.user.id).getRequestedUrl();
                                    //         console.info('onBeforeUploadItem', item);
                                    //     };
                                    //     $scope.uploader.uploadAll();
                                    // }
                    console.info('onBeforeUploadItem', item);
                };
                uploader.onProgressItem = function(fileItem, progress) {
                    console.info('onProgressItem', fileItem, progress);
                };
                uploader.onProgressAll = function(progress) {
                    console.info('onProgressAll', progress);
                };
                uploader.onSuccessItem = function(fileItem, response, status, headers) {
                    console.info('onSuccessItem', fileItem, response, status, headers);
                };
                uploader.onErrorItem = function(fileItem, response, status, headers) {
                    console.info('onErrorItem', fileItem, response, status, headers);
                };
                uploader.onCancelItem = function(fileItem, response, status, headers) {
                    console.info('onCancelItem', fileItem, response, status, headers);
                };
                uploader.onCompleteItem = function(fileItem, response, status, headers) {
                    console.info('onCompleteItem', fileItem, response, status, headers);
                };
                uploader.onCompleteAll = function() {
                    console.info('onCompleteAll');
                };
            }]
        });
        //附件上传列表组件
        formlyConfigProvider.setType({
            name: 'ui-dropfile',
            templateUrl: 'assets/views/customform/tpl/ui-dropfile.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            controller:['$scope', function ($scope) {
                if(angular.isUndefined($scope.form.dropState)){
                    $scope.form.dropState=false;
                }
                //附件上传数据
                var uploader = $scope.uploader = $scope.options.templateOptions.fileUploader;
                //$scope.options.templateOptions.uploader();
                
                // FILTERS
                uploader.filters.push({
                    name: 'customFilter',
                    fn: function(item /*{File|FileLikeObject}*/ , options) {
                        return this.queue.length < 10;
                    }
                });


                $scope.dropfile = function(APIService, processInstanceId, taskId, userId){
                    uploader.onBeforeUploadItem = function(item) {
                        item.url = APIService.saveAttachments(processInstanceId, taskId, userId).getRequestedUrl();
                        item.formData.push({'fileName':item.file.name});
                        console.info('onBeforeUploadItem', item);
                    };
                    uploader.uploadAll();
                }

                // CALLBACKS
                uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
                    console.info('onWhenAddingFileFailed', item, filter, options);
                };
                uploader.onAfterAddingFile = function(fileItem) {
                    console.info('onAfterAddingFile', fileItem);
                };
                uploader.onAfterAddingAll = function(addedFileItems) {
                    console.info('onAfterAddingAll', addedFileItems);
                };
                uploader.onBeforeUploadItem = function(item) {
                    // if($scope.uploader.getNotUploadedItems().length>0&&response.data.processInstanceId){
                                    //     // $scope.uploader.options.url();
                                    //     $scope.uploader.onBeforeUploadItem = function(item) {
                                    //         item.url = api_bpm_domain.saveAttachments($stateParams.processInstanceId,$stateParams.taskId,$scope.user.id).getRequestedUrl();
                                    //         console.info('onBeforeUploadItem', item);
                                    //     };
                                    //     $scope.uploader.uploadAll();
                                    // }
                    console.info('onBeforeUploadItem', item);
                };
                uploader.onProgressItem = function(fileItem, progress) {
                    console.info('onProgressItem', fileItem, progress);
                };
                uploader.onProgressAll = function(progress) {
                    console.info('onProgressAll', progress);
                };
                uploader.onSuccessItem = function(fileItem, response, status, headers) {
                    console.info('onSuccessItem', fileItem, response, status, headers);
                };
                uploader.onErrorItem = function(fileItem, response, status, headers) {
                    console.info('onErrorItem', fileItem, response, status, headers);
                };
                uploader.onCancelItem = function(fileItem, response, status, headers) {
                    console.info('onCancelItem', fileItem, response, status, headers);
                };
                uploader.onCompleteItem = function(fileItem, response, status, headers) {
                    console.info('onCompleteItem', fileItem, response, status, headers);
                };
                uploader.onCompleteAll = function() {
                    console.info('onCompleteAll');
                };
            }]
        });

        //附件下载列表组件
        formlyConfigProvider.setType({
            name: 'ui-dropfiletable',
            templateUrl: 'assets/views/customform/tpl/ui-dropfiletable.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        refresh:function(APIService,processInstanceId, data){
                           return APIService.listAttachments(processInstanceId, data);
                        },
                        downloadUri:function(APIService, contentId){
                           return APIService.downloadAttachment(contentId).getRequestedUrl();
                        },
                        refreshDelay: 0
                    }
                };
            },
            controller:['$scope', '$timeout', function ($scope,$timeout) {
                var _refreshDelayPromise;
                $scope.downloadUrl = function(contentId){
                    return $scope.options.templateOptions.downloadUri($scope.options.templateOptions.ApiService,contentId)||'#';
                };

                /**
                 * refresh
                 */
                $scope._refresh = function(refreshAttr) {
                    if (refreshAttr !== undefined) {
                      if (_refreshDelayPromise) {
                        $timeout.cancel(_refreshDelayPromise);
                      }
                      _refreshDelayPromise = $timeout(function() {
                        $scope.options.templateOptions.refresh($scope.options.templateOptions.ApiService,
                            $scope.options.templateOptions.processInstanceId,{'idx':0,'sum':1000}).then(function(response){
                                var myData = $scope.options.templateOptions.Restangular.stripRestangular(response);
                                if(myData){
                                    $scope.attachments = myData.data;
                                }                                
                            });
                      }, $scope.options.templateOptions.refreshDelay);
                    }
                }

                $scope._refresh({});
            }]
        });

        formlyConfigProvider.setType({
            name: 'ui-paralleltask',
            templateUrl: 'assets/views/customform/tpl/ui-paralleltask.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        refresh:function(APIService,processInstanceId, data){
                           //return APIService.listAttachments(processInstanceId, data);
                        },
                        refreshDelay: 0
                    }
                };
            },
            controller:['$scope', '$timeout', function ($scope,$timeout) {
            }]
        });

        //repeatSection
        //
        formlyConfigProvider.setType({
            name: 'ui-repeatSection',
            templateUrl: 'assets/views/customform/tpl/ui-repeatSection.html',
            defaultOptions:function(options){
                return {
                    templateOptions: {
                        unique:1,
                        initDisplay:false
                    }
                };
            },
            controller: function($scope) {
                //$scope.options.templateOptions.unique;
                $scope.formOptions = {formState: $scope.formState};
                $scope.addNew = addNew;
                
                $scope.copyFields = copyFields;
                
                function copyFields(fields) {
                  fields = angular.copy(fields);
                  addRandomIds(fields);
                  return fields;
                }
                
                function addNew() {
                  $scope.model[$scope.options.key] = $scope.model[$scope.options.key] || [];
                  var repeatsection = $scope.model[$scope.options.key];
                  var lastSection = repeatsection[repeatsection.length - 1];
                  var newsection = {};
                  // if (lastSection) {
                  //   newsection = angular.copy(lastSection);
                  // }
                  repeatsection.push(newsection);
                }
                
                function addRandomIds(fields) {
                    $scope.options.templateOptions.unique++;
                    angular.forEach(fields, function(field, index) {
                        if (field.fieldGroup) {
                          addRandomIds(field.fieldGroup);
                          return; // fieldGroups don't need an ID
                        }
                        
                        if (field.templateOptions && field.templateOptions.fields) {
                          addRandomIds(field.templateOptions.fields);
                        }
                        
                        field.id = field.id || (field.key + '_' + index + '_' + $scope.options.templateOptions.unique + getRandomInt(0, 9999));
                    });
                }
                
                function getRandomInt(min, max) {
                  return Math.floor(Math.random() * (max - min)) + min;
                }

                if($scope.options.templateOptions.initDisplay){
                    addNew();
                }
            }
        });
        //时间轴任务列表组件
        
        //列表组件
        
        //知识库按钮组件
        formlyConfigProvider.setType({
                name: 'ui-search',
                templateUrl: 'assets/views/customform/tpl/ui-knowledge.html',
                defaultOptions:function(options){
                    return {
                        templateOptions: {
                            search : function(size, options, modal, keys, fields, el){
                                var modalInstance = modal.open({
                                    templateUrl: 'assets/views/customform/tpl/search-knowledge.html',
                                    controller: function($scope, $modalInstance, searchKey, title, Restangular, APIService, modelscope,relatedAction) {
                                        $scope.options = {
                                            language: 'zh-cn',
                                            allowedContent: true,
                                            entities: false
                                        };

                                        $scope.onReady = function () {
                                                // ...
                                        };

                                        $scope.searchKey = searchKey;
                                        $scope.search=function(key){
                                            APIService.searchSolutionByKey(key).then(function(response){
                                                var myData = Restangular.stripRestangular(response);
                                                var status=myData.status;
                                                if(status=="500"){
                                                   //toaster.pop('warning', '没有数据', '查询'+keys+'没有数据');
                                                }else if(status=="200"){
                                                    var data=myData.data;
                                                    if(data.length>0){
                                                        $scope.searchData = data;
                                                    }
                                               }
                                            });
                                        };

                                        $scope.related = function(entity){
                                            // angular.forEach(fields, function(field){
                                            //     if(field.key == 'directClose'){
                                            //         field.value(true);
                                            //         modelscope.$parent.$parent.$parent.model['start_code']='close';
                                                   
                                            //     }
                                            //     if(field.key == 'handleDescription'){
                                
                                            //         field.model['handleDescription']=tentity.content;
                                            //     }
                                            // });
                                            
                                            if(relatedAction&&angular.isFunction(relatedAction)){
                                                relatedAction(fields, modelscope, entity);
                                            }
                                            $scope.cancel();
                                            // angular.forEach(fields,function(field){
                                                
                                            // });                                            
                                            
                                        }

                                        $scope.title = title;
                                        
                                        $scope.search(searchKey);

                                        $scope.selected = {
                                            item: {}
                                        };

                                        $scope.ok = function() {
                                            //console.log($scope.selected.item);
                                            $modalInstance.close($scope.selected.item);
                                        };

                                        $scope.cancel = function() {
                                            $modalInstance.dismiss('cancel');
                                        };
                                    },
                                    size: size,
                                    resolve: {
                                        searchKey: function() {
                                            return  keys;
                                        },
                                        title: function() {
                                            return options.templateOptions.modalTitle;
                                        },
                                        Restangular : function() {
                                            return options.templateOptions.Restangular;
                                        },
                                        APIService: function() {
                                            return options.templateOptions.ApiService;
                                        },
                                        modelscope: function(){
                                            return el.$parent;
                                        },
                                        relatedAction: function(){
                                            return options.templateOptions.relationAction;
                                        }
                                    }
                                });
                                // modalInstance.result.then(function(selectedItem) {
                                //     options.value(selectedItem);
                                // }, function() {
                                //     //console.log('Modal dismissed at: ' + new Date());
                                // });
                            }
                        }
                    };
                },
                controller: ['$scope',function($scope){
                    // $scope.searchModal = $scope.model[$scope.options.key];
                    // $scope.$watch('searchModal',function(newValue, oldValue){
                    //     if (newValue === oldValue) { return; }
                    //     if (newValue.flag == oldValue.flag) { return; }
                    //     if (angular.isDefined(newValue.flag)&&(newValue.flag==true)){
                    //         if (newValue.searchKey!=''&&angular.isDefined(newValue.searchKey)){
                    //             $scope.options.templateOptions.search('lg',$scope.options,newValue.searchKey);
                    //         }
                    //     }
                    // })
                    //
                }]
        });


        //cmdb控件
        formlyConfigProvider.setType({
                name: 'ui-cmdb',
                extends:'input',
                templateUrl: 'assets/views/customform/tpl/ui-cmdb.html',
             
        });
});

appFormly.run(function(formlyConfig, $parse){
    //formlyConfig.extras.fieldTransform=formlyConfig.extras.fieldTransform||[];
    var removeOnHideTransformer = function (fields, model) {
        return fields.map(function(field) {
            if (field.hideExpression && (!field.data || !field.data.dontRemoveOnHidden)) {
                addFieldRemoveOnHideWatcher(field);
            }
            if(field.type=="ui-title"){
                addFieldRemoveOnHideWatcher(field);
            }
            return field;
        });
    };

    formlyConfig.extras.fieldTransform = removeOnHideTransformer;

    function addFieldRemoveOnHideWatcher(field) {
      var watcher = getWatcher();
      if (field.watcher) {
        if (!angular.isArray(field.watcher)) {
          field.watcher = [field.watcher];
        }
        field.watcher.push(watcher);
      } else {
        field.watcher = watcher;
      }
    }

    function getWatcher() {
      return {
        expression: function(field) {
          return field.hide;
        },
        listener: function(field, newHide, oldHide, scope) {
          if (field.hide) {
            if(field.templateOptions.pkey){
                $parse(field.templateOptions.pkey+"." + field.key).assign(scope.model, undefined);
            }else{
                $parse(field.key).assign(scope.model, undefined);
            }
          }
          if(field.type=="ui-title"){
            $parse(field.key).assign(scope.model, undefined);
          }
        }
      };
    }
});

appFormly.controller('CustomformCtrl', ['$rootScope', '$scope', '$parse', '$injector', '$http','$q', '$state', '$stateParams', '$modal', '$timeout', '$interval', 'SweetAlert', 'FileUploader', 'i18nService', 'Restangular', 'UserRestangular', 'BpmRestangular','api_configure_form', 'api_bpm_domain', 'api_bpm_data', 'api_user_data',
    function ($rootScope, $scope, $parse, $injector, $http, $q, $state, $stateParams, $modal, $timeout, $interval, SweetAlert, FileUploader, i18nService, Restangular, UserRestangular, BpmRestangular, api_configure_form, api_bpm_domain, api_bpm_data, api_user_data) {
    //console.log($parse('Restangular')($scope));
    //console.log($injector.get('Restangular'));
 //console.log($stateParams);

    
     
    var vm = this;
    vm.options = {};
    vm.exampleTitle = ['expressionProperties','model property'];
    vm.fields=[];
    vm.model={};

    $scope.langs=i18nService.getAllLangs();
    $scope.lang = 'zh-cn';
    i18nService.setCurrentLang($scope.lang);
    //alert($rootScope.user.id,null,2);
    vm.model["loginUser"] = $rootScope.user;
    var that=$injector;
    var parse=$parse;

    var formKey = "";
    var pdKey = "";
    var modelWatch = "";
    if(angular.isDefined($stateParams.model)&&$stateParams.model!=""){
        modelWatch = JSON.parse($stateParams.model);

        // console.log("modelWatch:"+ JSON.stringify(modelWatch));
    }
    if(angular.isDefined($state.current.pdKey)&&$state.current.pdKey!=""){
        pdKey = $state.current.pdKey;
         
    }
    console.log("pdKey::"+JSON.stringify($state.current.title));
    if(angular.isDefined($stateParams.formKey)&&$stateParams.formKey!=""){
        formKey = $stateParams.formKey;
        // console.log("formKey::"+JSON.stringify($stateParams.formKey));
    }

    if(angular.isDefined($stateParams.model)){
        var formModel = $stateParams.model;
    }
    //用户测试数据，后续从header的auth中获取
    var userId = 2;
    userId = $rootScope.user.id;

    //==============处理表单设计数据  开始====================
    //处理组件加载后台数据选项的方法
    function refreshSelectOptions(searchVal, field) {
        if(field.templateOptions.optionsUrl){
            var process = BpmRestangular.all("");
            if(field.templateOptions.ApiService){
                process = UserRestangular.all("");
            }
            
            process.customPOST({"idx":0,"sum":1000},field.templateOptions.optionsUrl).then(function(result){
                if(!field.templateOptions.options){
                    field.templateOptions.options=[];
                }
                if(field.templateOptions.optionsDataKey){
                    field.templateOptions.options =result[field.templateOptions.optionsDataKey];
                }else{
                    field.templateOptions.options =result;
                }
            });
        }
    }



    //解析自定义表单设计数据
    function decodeVMForm(vmForm){
        var result = {model:{},fields:[]};
        //设置模型实体数据 begin
//        var mdata = vmForm.model;
        //解析数据实体
        var mdata = angular.fromJson(vmForm.model);//JSON.parse(field.extjson);
        angular.extend(result.model,mdata);

        if(modelWatch != null && modelWatch != ''){
            //angular.extend(result.model.incident,modelWatch.incident);
            //result.model.alarmType = modelWatch.alarmType;
            // vmForm.cancelUrl = modelWatch.cancelUrl;
            for(var index in modelWatch.model){
                //console.log(JSON.stringify(index+" " +JSON.stringify( modelWatch.model[index])));
                if(result.model[index] != null){
                    angular.extend(result.model[index],modelWatch.model[index]);
                }else{
                    result.model[index] = modelWatch.model[index];
                }
            }
        }
        //设置模型实体数据 end
        //解析设计数据生成表单项 begin
        var fields = [];
        //处理修改设计数据中展示设置
        angular.forEach(vmForm.fields,function(field){
            if(field.key==""){
                delete field.key;
            }

            if(angular.isDefined(field.extjson)){
                var extObj = angular.fromJson(field.extjson);//JSON.parse(field.extjson);
                angular.extend(field.templateOptions, extObj.templateOptions);
                delete extObj.templateOptions;
                for(var prop in extObj){
                    if(new RegExp("Expression").test(prop)){
                        //var obj = $scope.$eval(extObj[prop]);
                        //extObj[prop] = $scope.$eval(extObj[prop]);
                        if(extObj[prop]!=null){
                            if(new RegExp("function").test(extObj[prop])){
                                var propValue = eval(extObj[prop]);
                                extObj[prop] = propValue;
                            }else{
                                //console.log(extObj[prop]);
                                var obj = $scope.$eval(extObj[prop]);
                                extObj[prop] = obj;
                                //console.log(obj);
                            }
                        }
                    }else if(new RegExp("expressionProperties").test(prop)){
                        for(var p in extObj[prop]){
                            if(new RegExp("function").test(extObj[prop][p])){
                                var propValue = eval(extObj[prop][p]);
                                extObj[prop][p] = propValue;
                            }else{
                                //if(p.indexOf("'")>=0){
                                // var obj = $scope.$eval(extObj[prop][p]);
                                // extObj[prop][$scope.$eval(p)]=obj;
                                //}
                            }
                         }
                    }else if("watcher"==prop){
                        if(angular.isArray(extObj[prop])){
                            angular.forEach(extObj[prop],function(item,index){
                                for(var p in item){
                                    if(new RegExp("function").test(item[p])){
                                        var propValue = eval(item[p]);
                                        extObj[prop][index][p] = propValue;
                                    }
                                }
                            });
                        }else if(angular.isObject(extObj[prop])){
                            for(var p in extObj[prop]){
                                if(new RegExp("function").test(extObj[prop][p])){
                                    var propValue = eval(extObj[prop][p]);
                                    extObj[prop][p] = propValue;
                                }
                            }
                        }
                    }
                }
                angular.extend(field,extObj);
                delete field.extjson;
            }


            if(angular.isDefined(field.templateOptions)){
                var templateOs = field.templateOptions;
                for(var property in templateOs){
                    //console.log(angular.isString(templateOs[property]) +"    "+property + "    " + (!(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property]))));
                    if(angular.isString(templateOs[property])){  //&& !(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property]))
                        if(new RegExp("function").test(templateOs[property])){
                            var propValue = eval(templateOs[property]);
                            field.templateOptions[property] = propValue;
                        }else{
                            if(that.has(templateOs[property])){
                                field.templateOptions[property] = that.get(templateOs[property]);
                            }else{
                                field.templateOptions[property] = templateOs[property];
                            }
                        }
                    }else if(templateOs[property]==null){
                        //delete field.templateOptions[property];
                    }else{
                    }
                }
            }
            //console.log(field);
            if(angular.isDefined(field.templateOptions) && angular.isDefined(field.templateOptions.extjson)){
                var extObj = angular.fromJson(field.templateOptions.extjson);//JSON.parse(field.extjson);
                angular.extend(field.templateOptions,extObj);
                delete field.templateOptions.extjson;
            }
            //...
            if(field.templateOptions){
                //处理远程获取数据控件方法调用
                if(field.templateOptions.optionsUrl){
                    field.templateOptions.refresh = refreshSelectOptions;
                }
                //事件脚本处理
//                if(field.templateOptions.ngChangeScript){
//                    if(!field.expressionProperties)field.expressionProperties={};
//                    field.expressionProperties.ngChange = function(modelVal,viewVal,ev){
////                        console.log(ev);
////                        console.log("change>>"+ev.options.key);
//                        eval(field.templateOptions.ngChangeScript);
//                    }
//                }
//                if(field.templateOptions.ngClickScript){
//                    if(!field.expressionProperties)field.expressionProperties={};
//                    field.expressionProperties.ngClick = function(modelVal,viewVal,ev){
////                        console.log(ev);
////                        console.log("click>>"+ev.options.key);
//                        eval(field.templateOptions.ngClickScript);
//                    }
//                }

                //处理嵌套属性数据绑定/
                if(field.templateOptions.pkey){
                    var pmodel,i= 0;
                    angular.forEach(field.templateOptions.pkey.split("."),function(p){
                        if(i==0){
                            if(result.model[p]==null){
                                result.model[p] = {};
                            }
                            pmodel = result.model[p];
                            i++;
                        }else{
                            if(pmodel[p]==null){
                                pmodel[p] = {};
                            }
                            pmodel = pmodel[p];
                        }
                    });
                    if(pmodel!=null){
                        field.model = pmodel;
                        if(pmodel[field.key]==null){
                            pmodel[field.key] = null;
                        }
                    }
                }else{
                    if(result.model[field.key]==null){
                        result.model[field.key] = null;
                    }
                }
                //处理弹出框组件初始化
                if(field.type=="ui-input-selectmodal"){
                    field.templateOptions.modal = $modal;
                    //field.templateOptions.Restangular = Restangular;
                }else if(field.type=="ui-requesterselect"){
                    //field.templateOptions.language = $scope.lang;
                    field.templateOptions.modal = $modal;
                    field.templateOptions.UserService = api_user_data;
                }else if(field.type=="ui-userselect"){
                    field.templateOptions.modal = $modal;
                    //field.templateOptions.Restangular = Restangular;
                }else if(field.type=="ui-multiuserselect"){
                    field.templateOptions.modal = $modal;
                }else if(field.type=="ui-search"){
                    field.templateOptions.modal = $modal;
                }else if(field.type=="ui-modelselect"){
                    field.templateOptions.modal = $modal;
                    //console.log("$rootScope.user:" + JSON.stringify($rootScope.user));
                    field.templateOptions.loginUser = $rootScope.user;
                    //field.templateOptions.Restangular = Restangular;
                }else if(field.type=="ui-dropfile"){
                    $scope.fileUploader = field.templateOptions.fileUploader = new FileUploader({
                        url:'/uploader'
                    });
                    field.templateOptions.taskId = $stateParams.taskId;
                    field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                    field.templateOptions.userId = $rootScope.user.id;
                    //field.ApiService=api_bpm_domain;
                }else if(field.type=="ui-dropfilenotup"){
                    $scope.fileUploader = field.templateOptions.fileUploader = new FileUploader({
                        url:'/uploader'
                    });
                    field.templateOptions.taskId = $stateParams.taskId;
                    field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                    field.templateOptions.userId = $rootScope.user.id;
                    //field.ApiService=api_bpm_domain;
                }
                else if(field.type=="ui-dropfiletable"){
                    if(field.templateOptions.processInstanceId){
                        
                    }else{
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                    }
                }else if(field.type=="ui-repeatSection"){
                    var repeatForm = {
                        model:{

                        },
                        fields:field.templateOptions.fields
                    };
                    repeatForm.model[field.key]=[];
                    decodeVMForm(repeatForm);
                }else if(field.type=="ui-currentuser"){
                    field.templateOptions.user = vm.model["loginUser"];
                }
            }

//          console.log(field);
            result.fields.push(field);
        });
        angular.extend($scope.vm.fields,result.fields);
        angular.extend($scope.vm.model,result.model);
         
        // console.log("$scope.vm.model="+JSON.stringify($scope.vm.model));
        vm.model["loginUser"] = $rootScope.user;
        if(modelWatch != null && modelWatch != '' && modelWatch.cancelUrl != null && modelWatch.cancelUrl != ''){
            vmForm.cancelUrl = modelWatch.cancelUrl;
        }
        $scope.formData = vmForm;
        // console.log("$scope.formData="+JSON.stringify($scope.formData.url));
        if($scope.formData.url=="start"){
             $scope.Reset=true;
             $scope.close=false;
         }else if($scope.formData.url=="complete"){
             $scope.Reset=false;
             $scope.close=true;
         }

        //解析设计数据生成表单项 end
        return result;
    }
    //======================处理表单设计数据  结束========================
    $scope.ldloading = {};

    function filter(obj) {
        angular.forEach(obj, function(key, value){
            if (value === "" || value === null){
                delete obj[key];
            } else if (Object.prototype.toString.call(value) === '[object Object]') {
                filter(value);
            } else if (angular.isArray(value)) {
                angular.forEach(value,function(item){
                    filter(item);
                });
            }
        });
    }
     
    $scope.closeModel = function(){
       console.log("pdKey="+pdKey);
    if(pdKey=="bpm_incident") { 
    $state.go('app.incident.list',{ });
    }else if(pdKey=="bpm_change"){
      $state.go('app.change.list',{ });  
    }else if(pdKey=="bpm_problem"){
      $state.go('app.problem.list',{ });  
    }else if(pdKey=="bpm_release"){
      $state.go('app.release.list',{ });  
    }else if(pdKey=="bpm_schedule"){
      $state.go('app.scheduling.list',{ });  
    }
    event.preventDefault(); 
    } ;
    vm.submit = function(data, style){
        if (vm.form.$valid) {
            // console.log("vm.options:"+ JSON.stringify(vm.options));
            vm.options.updateInitialValue();
            // console.log("dfjkasdhfkhskjf ")
            $scope.ldloading[style.replace('-', '_')] = true;
            var _ = window._;
            vm.model = (function filter(obj) {
                var dateTransKeys=[];
                var filtered = _.pick(obj, function (v,k,obj) {
                    if(_.isDate(v)){
                        dateTransKeys.push(k);
                    }

                    return angular.isDefined(v) && v !== null && (angular.isArray(v)?v.length>0:true) && (_.isPlainObject(v)?(!_.isEmpty(v)):true);  
                });
                 
                return _.cloneDeep(filtered, function (v,index,object) { 
                    if(angular.isArray(dateTransKeys)&&dateTransKeys.length>0){
                        angular.forEach(dateTransKeys,function(item){
                            v[item]=moment(v[item]).format('YYYY-MM-DD HH:mm:ss');

                        })
                        dateTransKey = [];
                        return v;
                    }
                     
                    return !(_.isEmpty(filtered)) && v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; 
                });
            })(vm.model);
            
             
            if(pdKey!=""){
      
                if($scope.oprcode=="save"){//保存
                    api_bpm_domain.save(taskId, vm.model).then(function(response){
                        if(response){
                            var resData = Restangular.stripRestangular(response);
                            SweetAlert.swal({
                                title: "保存成功!",
                                confirmButtonColor: "#007AFF"
                            },function(){

                                $state.go($scope.formData.cancelUri);
                            });
                            // if(resData.status){
                            //     resData
                            // }
                        }else{
                            SweetAlert.swal({
                              title: "系统错误",
                              text: "系统错误，请稍后重试!",
                              type: "error",
                              confirmButtonColor: "#DD6B55"
                            });
                        }
                        $scope.ldloading[style.replace('-', '_')] = false;
                    });
                }else{
                    
                     
                    switch($scope.formData.url){

                    case "start" :
                        vm.model["initUser"]=$rootScope.user.id;
                        if(vm.model["assignee"]||vm.model["candidateGroups"]){

                        }else{
                            vm.model["assignee"]=$rootScope.user.id;
                        }                        
                        api_bpm_domain.start(pdKey,vm.model).then(function(response){

                           // console.log("response="+JSON.stringify(response)); 
                            if(response){
                                var resData = Restangular.stripRestangular(response);
                                if(resData){

                                   // console.log("$scope.fileUploader="+$scope.fileUploader)
                                    if($scope.fileUploader != null && $scope.fileUploader.getNotUploadedItems().length>0&&resData.id){
                                        //$scope.uploader.options.url();
                                        $scope.fileUploader.onBeforeUploadItem = function(item) {
                                            item.url = api_bpm_domain.saveAttachments(resData.id,'00000',$rootScope.user.id).getRequestedUrl();
                                            item.formData.push({'fileName':item.file.name});
                                            //console.log();
                                        };
                                        $scope.fileUploader.uploadAll();
                                    }
                                }

                                SweetAlert.swal({
                                    title: "提交成功!",
                                    confirmButtonColor: "#007AFF"
                                },function(){
                                    $state.go($scope.formData.cancelUrl);
                                });
                            }else{
                                SweetAlert.swal({
                                  title: "系统错误",
                                  text: "系统错误，请稍后重试!",
                                  type: "error",
                                  confirmButtonColor: "#DD6B55"
                                });
                            }
                            $scope.ldloading[style.replace('-', '_')] = false;

                        });
                        break;
                    case "complete" :
    //                    api_bpm_domain.complete(pdKey, userId, vm.model).then(function(response){
                        //console.log("complete taskId::"+$stateParams.taskId);
                        api_bpm_domain.complete($stateParams.taskId, userId, vm.model).then(function(response){
                            if(response){
                                var resData = Restangular.stripRestangular(response);
                                SweetAlert.swal({
                                    title: "提交成功!",
                                    confirmButtonColor: "#007AFF"
                                },function(){
                                    // if($scope.uploader.getNotUploadedItems().length>0&&response.data.processInstanceId){
                                    //     // $scope.uploader.options.url();
                                    //     $scope.uploader.onBeforeUploadItem = function(item) {
                                    //         item.url = api_bpm_domain.saveAttachments($stateParams.processInstanceId,$stateParams.taskId,$scope.user.id).getRequestedUrl();
                                    //         console.info('onBeforeUploadItem', item);
                                    //     };
                                    //     $scope.uploader.uploadAll();
                                    // }
                                    $state.go($scope.formData.cancelUrl);
                                });
                            }else{
                                SweetAlert.swal({
                                  title: "系统错误",
                                  text: "系统错误，请稍后重试!",
                                  type: "error",
                                  confirmButtonColor: "#DD6B55"
                                });
                            }
                            $scope.ldloading[style.replace('-', '_')] = false;
                        });
                        break;
                    case "back" :
                        $state.go($scope.formData.cancelUrl);
                        break;
                    default:
                        $scope.ldloading[style.replace('-', '_')] = false;
                        break;
                    }
                }
                // var submitFunc = api_bpm_domain[$scope.formData.url]
                // if(anuglar.isFunction(submitFunc)){
                //     submitFunc.apply(null, pdKey)
                // }
            }
        }else{
            SweetAlert.swal({
              title: "校验错误",
              text: "请填写必填项!",
              type: "error",
              confirmButtonColor: "#DD6B55"
            });
            angular.forEach(vm.form.$error.required, function(item){
                 angular.forEach(vm.fields,function(f){
                    if(f.name == item.$name){
                        f.validation.show = true;
                    }
                 });
            })
        }
    };
     
    $scope.vm = vm;

    if(angular.isDefined($stateParams.taskId)&&$stateParams.taskId!=""){
       // console.log("taskId>>"+$stateParams.taskId);
        // editor process task form
        var processInstanceId = $stateParams.processInstanceId;
        api_bpm_domain.taskformkey($stateParams.taskId).then(function(response){
            if(response){
                var myData = Restangular.stripRestangular(response);//console.log("myData>>>");console.log(myData);
                api_configure_form.renderForm(myData.data,userId, processInstanceId).then(function(responseData){
                    if(responseData){//console.log("responseData>>>");//console.log(responseData);
                        var vmForm = Restangular.stripRestangular(responseData);
                        if(vmForm){//console.log("vmForm>>>");//console.log(vmForm);
                            decodeVMForm(vmForm);
                            //console.log($scope);
                        }
                    }
                });
            }
        })
    }else{
        // create process instance
        if(pdKey!=""){//for process
            api_bpm_domain.startformkey(pdKey).then(function(response){
                if(response){
                    var myData = Restangular.stripRestangular(response);
                    //myData.data = "arrangeform";
                    api_configure_form.renderForm(myData.data,userId).then(function(responseData){
                        if(responseData){
                            var vmForm = Restangular.stripRestangular(responseData);
                            if(vmForm){
                                decodeVMForm(vmForm);
                                //console.log($rootScope);
                            }
                        }
                    });
                }
            });
        }else{//for form
            //TODO
            //测试数据 开始
            var testJson = {
                fields : [
                    {
                        key: 'formtitle',
                        type: 'ui-title',
                        noFormControl: true,
                        templateOptions: {
                            label: 'title is ',
                            placeholder: 'Formly is terrific!'
                        }
                    },
                    // {
                    //     key:'a',type:'ui-input',className:'col-xs-4',
                    //     templateOptions: {
                    //         type: 'input',label: 'input a',placeholder:'search a...',
                    //         lBtn:{
                    //             label:'input',
                    //             onClick: function(val,opt,el,ev,model){alert(val);}
                    //         },
                    //         rAddon:'@111.cc'
                    //     }
                    // },
                    {
                        key:'b',type:'ui-input',className:'col-xs-4',
                        templateOptions: {
                            type: 'input',label: 'input a',placeholder:'search a...',
                            rBtn:{
                                icon:'fa fa-phone',
                                onClick: function(val,opt,el,ev,model){alert(val);}
                            },
                            lAddon:'<i class="fa fa-phone"/>'
                        }
                    },
                    // {
                    //     key:'first',type:'ui-input',className:'col-xs-2',
                    //     templateOptions: {
                    //         type: 'input',
                    //         label: 'first name',
                    //         pkey:'name'
                    //     }
                    // },                    
                    // {
                    //     key:'first',type:'ui-number',className:'col-xs-3',
                    //     templateOptions: {
                    //         label: '时长',
                    //         pkey:'name',
                    //         min:0,
                    //         rAddon:'分钟'
                    //     }
                    // },
                    // {
                    //     key:'last',type:'ui-input',className:'col-xs-2',
                    //     templateOptions: {type: 'input',label: 'last name',pkey:'name'}},
                    //     {
                    //         key:'username',
                    //         type:'ui-input',
                    //         className:'col-xs-4',
                    //         templateOptions: {
                    //             type: 'input',
                    //             label: 'User Name',
                    //             placeholder: 'Enter name',
                    //             required:true,
                    //             maxLength:10
                    //     }
                    // },
                    // {
                    //     key: 'password',
                    //     type: 'ui-input',
                    //     className:'col-xs-4',
                    //     templateOptions: {
                    //         type: 'password',
                    //         label: 'Password',
                    //         placeholder: 'Password',
                    //         required:true
                    //     },
                    //     expressionProperties: {
                    //         'templateOptions.disabled': '!model.username'
                    //     }
                    // },
                    // {
                    //     key: 'selectmodal',
                    //     type: 'ui-input-selectmodal',
                    //     className:'col-xs-6',
                    //     templateOptions:{
                    //         label: 'selectmodal',
                    //         btnLabel:'search',
                    //         btnClassName:'btn-o',
                    //         modalParam:{
                    //             items:  function(){
                    //                 return ['a','b','c','d'];
                    //             },
                    //             title: function(){
                    //                 return '测试标题';
                    //             }
                    //         }
                    //     }
                    // },
                    // {
                    //     key: 'email',
                    //     type: 'ui-input',
                    //     className:'col-xs-6',
                    //     templateOptions:{
                    //         type: 'email',
                    //         maxlength: 10,
                    //         minlength: 6,
                    //         label: 'EMail'
                    //     }
                    // },
                    // {
                    //     key: 'date',
                    //     type: 'ui-datepicker',
                    //     className:'col-xs-6',
                    //     templateOptions: {
                    //         label: 'Date',
                    //         type: 'text',
                    //         datepickerPopup: 'yyyy-MM-dd hh:mm:ss',
                    //         initDate : function(){
                    //             return new Date();
                    //         }

                    //     }
                    // },
                    {
                        key: 'multiselectItem',
                        type: 'ui-multi-select-tree',
                        className: 'col-xs-6',
                        templateOptions:{
                            label: 'multiSelect',
                            placeholder:'请选择...',
                            isMultiSelect:false,
                            selLeafs:false,//只选叶子节点
                            refreshData: function(APIService){
                                return APIService.fetchDataList('changeclassify',{'idx':0,'sum':100});
                            },
                            APIService:api_bpm_data,
                            optionsDataKey:'list',
                            refreshDelay:1000,
                            onDataCallback:function(item, selectItems,  options, field, model){
                                model[options.key]={id:item.id};
                                // console.log("item="+JSON.stringify(model))
                            }
                        }
                    },
                    // {
                    //     key:'selectItem',
                    //     type:'ui-select',
                    //     className:'col-xs-4',
                    //     templateOptions:{
                    //         label:'ui-select',
                    //         valueProp: 'code',//对应value
                    //         labelProp: 'source',//对应key
                    //         optionsUrl:'data/fetchDataList/incidentsource',//对应后台地址，api/之前的部分省略
                    //         optionsDataKey:'list',//对应返回数组数据的键值,
                    //         required:true,
                    //         onChange:function(val, options, field, event ,model){
                    //             model.start_code = val;
                    //         }
                    //     }
                    // },
                    // {
                    //     key:'id',
                    //     type:'ui-multiselect',
                    //     className:'col-xs-4',
                    //     templateOptions:{
                    //         label:'multi-select',
                    //         pkey:"change.systemType",
                    //         valueProp: 'id',//对应value
                    //         labelProp: 'source',//对应key
                    //         optionsUrl:'data/fetchDataList/changesystemtype',//对应后台地址，api/之前的部分省略
                    //         optionsDataKey:'list',//对应返回数组数据的键值,
                    //         required:true,
                    //         onChange:function(val, options, field, event ,model){
                    //             console.log(val);
                    //             console.log(model);
                    //             //model.start_code = val;
                    //         }
                    //     }
                    // },
                    {
                        key:'checklistItem',
                        type:'ui-checklist',
                        className:'col-xs-4',
                        templateOptions: {
                            label:'checklistItem',
                            options: [
                                {name: 'Iron Man', value: 'iron_man'},
                                {name: 'Captain America', value: 'captain_america'},
                                {name: 'Black Widow', value: 'black_widow'},
                                {name: 'Hulk', value: 'hulk'},
                                {name: 'Captain Marvel', value: 'captain_marvel'}
                            ]
                        }
                    },
                    {
                        key:'radioItem',
                        type:'ui-radio',
                        className:'col-xs-8',
                        templateOptions:{
                            label:'radioItem',
                            options: [
                                {name: 'Iron Man', value: 'iron_man'},
                                {name: 'Captain America', value: 'captain_america'},
                                {name: 'Black Widow', value: 'black_widow'},
                                {name: 'Hulk', value: 'hulk'},
                                {name: 'Captain Marvel', value: 'captain_marvel'}
                            ],type:'number'
                        }
                    },
                    // {
                    //     key:'selectUser',
                    //     type:'ui-userselect',
                    //     className:'col-xs-12',
                    //     templateOptions:{
                    //         label:'请求人信息',
                    //         modalTitle:'请求人列表',
                    //         fetchItems:function(filterData, APIService){
                    //             return APIService.fetchDataList('user',filterData);
                    //         },
                    //         Restangular:Restangular,
                    //         ApiService:api_user_data,
                    //         onClick:function(val, options, field, event , model){
                    //             //model.start_code++;
                    //             console.log(options);
                    //         }
                    //     }
                    // },
                    {
                        key:'selectUser',
                        type:'ui-requesterselect',
                        className:'col-xs-12',
                        templateOptions:{
                            label:'请求人信息',
                            modalTitle:'请求人列表',
                            fetchItems:function(filterData, APIService){
                                return APIService.fetchDataList('requester',filterData);
                            },
                            Restangular:Restangular,
                            ApiService:api_user_data
                            // onClick:function(val, options, field, event , model){
                            //     console.log(options);
                            // }
                        }
                    },
                    {
                        key:'cabUser',
                        type:'ui-multiuserselect',
                        className:'col-xs-12',
                        templateOptions:{
                            label:'CAB评审成员',
                            modalTitle:'CAB成员列表',
                            fetchItems:function(filterData, APIService){
                                return APIService.fetchDataList('user',filterData);
                            },
                            Restangular:Restangular,
                            ApiService:api_user_data,
                            onClick:function(val, options, field, event , model){
                               // console.log(model);
                            }
                        }
                    },
                    // {
                    //     key:'incident',
                    //     type:'ui-modelselect',
                    //     className:'col-xs-3',
                    //     templateOptions:{
                    //         label:'关联事件工单',
                    //         modalTitle:'事件列表',
                    //         fetchItems:function(filterData,APIService){
                    //             return APIService.fetchDataList('incident',filterData);
                    //         },
                    //         Restangular:"Restangular",
                    //         ApiService:"api_bpm_data",
                    //         columnDefs:[
                    //                     { name:'id', width:80, enableFiltering:false},
                    //                     { name:'title', displayName:'事件主题', width:140},
                    //                     { name:'type.name', displayName:'事件类型', width:140},
                    //                     { name:'emergency.name', displayName:'紧急度', width:80},
                    //                     { name:'state.name', displayName:'状态', width:100},
                    //                     { name:'emergency.name', displayName:'紧急度', width:80},
                    //                     { name:'influence.name', displayName:'影响度', width:80},
                    //                     { name:'priority.name', displayName:'优先级', width:80},
                    //                     { name:'handlerUser.name', displayName:'当前处理人', width:100},
                    //                     { name:'acceptDate', displayName:'创建时间', width:100}                                        
                    //         ],
                    //         displayName:'title', 
                    //         onClick:function(val, options, field, event , model){
                    //             //model.start_code++;
                    //             console.log(options);
                    //         }
                    //     }
                    // },
                    // {
                    //     key: 'worknumber',
                    //     type: 'ui-workernumber',
                    //     className:'col-xs-3',
                    //     templateOptions: {
                    //         label: 'work number',
                    //         Restangular:Restangular,
                    //         ApiService:api_bpm_domain,
                    //         getWorkernumber: function(APIService){
                    //             return APIService.workernumber('bg');
                    //         }
                    //     }
                    // },
                    // {
                    //     key: 'chkme',
                    //     type: 'ui-checkbox',
                    //     className:'col-xs-3',
                    //     templateOptions: {
                    //         label: 'Check me out'
                    //     }
                    // },
                    // {
                    //     key: 'droplink',
                    //     type: 'ui-link',
                    //     className: 'col-xs-3',
                    //     templateOptions:{
                    //         label:'添加附件',
                    //         onClick:function(val, options, field, event ,model){
                    //             if(angular.isUndefined(field.form.dropState)){
                    //                 field.form.dropState=false;
                    //             }
                    //             field.form.dropState=!field.form.dropState;  
                    //             console.log(field);
                    //         }
                    //     }
                    // },
                    // {
                    //     key: 'dropfile',
                    //     type: 'ui-dropfile',
                    //     className: 'col-xs-12',
                    //     templateOptions:{
                    //         label:'附件',
                    //         uploadUrl:'http://127.0.0.1:9008/saveAttachments'
                    //     }
                    // },
                    // {
                    //     type: 'ui-label',
                    //     key: 'changesign',
                    //     className: 'col-xs-4',
                    //     templateOptions: {
                    //         label:'变更请求单号',
                    //         pkey:'change'
                    //     }
                    // },
                    // {   
                    //     type: 'ui-label',
                    //     key: 'title',
                    //     className: 'col-xs-4',
                    //     templateOptions: {
                    //         label:'变更标题',
                    //         pkey:'change'
                    //     }
                    // },
                    // //关联发布单号
                    // //新建发布                    
                    // {
                    //     key: 'droplist',
                    //     type: 'ui-dropfiletable',
                    //     className: 'col-xs-12',
                    //     templateOptions:{
                    //         label:'附件下载列表',
                    //         Restangular:Restangular,
                    //         processInstanceId:'250033',
                    //         ApiService:api_bpm_domain
                    //     }
                    // },
                    // {
                    //     type: 'ui-repeatSection',
                    //     key: 'investments',
                    //     className: 'col-xs-12',
                    //     templateOptions: {
                    //         btnText: '新增变更施工单',
                    //         fields: [
                    //             {
                    //                 className: 'col-xs-3',
                    //                 type: 'ui-input',
                    //                 key: 'aboutci',
                    //                 templateOptions: {
                    //                     label: '关联的配置项',
                    //                     required: true
                    //                 }
                    //             },
                    //             {
                    //                 className: 'col-xs-3',
                    //                 type: 'ui-datepicker',
                    //                 key: 'planbegintime',
                    //                 templateOptions: {
                    //                     label: '计划开始时间',
                    //                     required: true
                    //                 }
                    //             },   
                    //             {
                    //                 className: 'col-xs-3',
                    //                 type: 'ui-datepicker',
                    //                 key: 'planendtime',
                    //                 templateOptions: {
                    //                     label: '计划完成时间',
                    //                     required: true
                    //                 }
                    //             },
                    //             {
                    //                 className: 'col-xs-12',
                    //                 type: 'ui-userselect',
                    //                 key: 'handleruser',
                    //                 templateOptions: {
                    //                     label: '实施人员信息',
                    //                     modalTitle:'实施人列表',
                    //                     required: true,
                    //                     fetchItems:function(filterData, APIService){
                    //                         return APIService.fetchDataList('user',filterData);
                    //                     },
                    //                     Restangular:Restangular,
                    //                     ApiService:api_user_data,
                    //                     onClick:function(val, options, field, event , model){
                    //                         //model.start_code++;
                    //                         console.log(options);
                    //                     }
                    //                 }
                    //             },
                    //             {
                    //                 className: 'col-xs-8',
                    //                 type: 'ui-textarea',
                    //                 key: 'handlerContent',
                    //                 templateOptions: {
                    //                     label: '实施内容',
                    //                     required: true,
                    //                     row:10
                    //                 }
                    //             },{
                    //                 noFormControl: true,
                    //                 template:'<hr>'
                    //             }]
                    //     }
                    // },
                    // {
                    //     key: 'droplist',
                    //     type: 'ui-dropfiletable',
                    //     className: 'col-xs-12',
                    //     templateOptions:{
                    //         label:'附件下载列表',
                    //         Restangular:Restangular,
                    //         processInstanceId:'250033',
                    //         ApiService:api_bpm_domain
                    //     }
                            
                    // },
                    // {
                    //     key: 'start_code',
                    //     className:'col-xs-6',
                    //     type: 'ui-hidden'
                    // },
                    // {
                    //     key:'remark',
                    //     type:'ui-textarea',
                    //     className:'col-xs-12',
                    //     templateOptions:{
                    //         label:'remark is ',
                    //         rows:3
                    //     }
                    // },
                    {
                        key:'setStartCode',
                        type:'ui-button',
                        className:'col-xs-4',
                        templateOptions:{
                            label:'升级为变更',
                            onClick:function(val, options, field, event ,model){
                                //console.log(options);
                                event.preventDefault();
                                //model.start_code++;
                                //console.log(options);
                            }
                        }
                    }
                ],
                model : {
                    username:"robin lau",
                    password:"123456",
                    chkme:false,start_code:0,
                    formtitle:"Hey!I am title value!",
                    name:{
                        first:"robin",last:"lau"
                    },
                    multiselectItem:[]
                    //date:"2015-09-15 00:00:00"
                }
            };
            setTimeout(function(){
                decodeVMForm(testJson);
                $scope.$apply();
            },500);
            //测试数据结束
        }
    }
    //console.log("end decode");
}]);


